package com.genghis.rapidcrm.web.view;

import com.genghis.rapidcrm.exception.RuntimeGoingException;
import com.genghis.rapidcrm.kernel.UsersPrivilegesModel;
import com.genghis.rapidcrm.kernel.UsersRecordModel;
import com.genghis.rapidcrm.kernel.module.RapidModuleModel;
import com.genghis.rapidcrm.web.view.model.RapidJsScriptModel;
import edu.jetwinner.common.EasyStringUtil;
import edu.jetwinner.common.FastHashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * @author xulixin
 */
public class RapidIndexView extends RapidBasicView {

    boolean checkPermission(HttpServletRequest request) {
        //Return true as WebUI.php is already checking for module permission
        return true;
    }

    @Override
    public void preProcess(HttpServletRequest request, HttpServletResponse response, boolean display)
            throws Exception {

        super.preProcess(request, response, false);

        UsersRecordModel currentUser = UsersRecordModel.getCurrentUserModel(request);

        RapidViewer viewer = this.getViewer(request);

        String moduleName = getModule(request);
        if (EasyStringUtil.isNotBlank(moduleName)) {
            RapidModuleModel moduleModel = getModuleModelInstance(moduleName);
            UsersPrivilegesModel userPrivilegesModel = getApplicationContext().getBean(UsersPrivilegesModel.class)
                    .getInstanceById(currentUser.getId());

            boolean permission = userPrivilegesModel.hasModulePermission(moduleModel.getId());
            viewer.assign("MODULE", moduleName);

            if (!permission) {
                viewer.assign("MESSAGE", "LBL_PERMISSION_DENIED");
                viewer.view("OperationNotPermitted.tpl", moduleName, request, response);
                throw new RuntimeGoingException("Current user do not access module: " + moduleName);
            }

            Map<String, Object> linkParams = FastHashMap.build(2)
                    .add("MODULE", moduleName).add("ACTION", request.getParameter("view")).toMap();

            viewer.assign("QUICK_LINKS", moduleModel.getSideBarLinks(linkParams));
        }

        viewer.assign("CURRENT_USER_MODEL", currentUser);
        viewer.assign("CURRENT_VIEW", request.getParameter("view"));
        if (display) {
            this.preProcessDisplay(request, response);
        }
    }

    @Override
    protected String preProcessTplName(HttpServletRequest request) {
        return "IndexViewPreProcess.tpl";
    }

    //Note : To get the right hook for immediate parent in PHP,
    // specially in case of deep hierarchy
	/*function preProcessParentTplName(Vtiger_Request $request) {
		return parent::preProcessTplName($request);
	}*/

    @Override
    public void postProcess(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String moduleName = getModule(request);
        RapidViewer viewer = this.getViewer(request);
        viewer.view("IndexPostProcess.tpl", moduleName, request, response);

        super.postProcess(request, response);
    }

    @Override
    public void process(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String moduleName = getModule(request);
        RapidViewer viewer = this.getViewer(request);
        viewer.view("Index.tpl", moduleName, request, response);
    }

    /**
     * Function to get the list of Script models to be included
     *
     * @param request
     * @return <Array> - List of Vtiger_JsScript_Model instances
     */
    @Override
    protected List<RapidJsScriptModel> getHeaderScripts(HttpServletRequest request) {
        List<RapidJsScriptModel> headerScriptInstances = super.getHeaderScripts(request);
        String moduleName = getModule(request);

        String[] jsFileNames = {"modules.Vtiger.resources.Vtiger",
                String.format("modules.%s.resources.%s", moduleName, moduleName)};

        Map<String, RapidJsScriptModel> jsScriptInstances = this.checkAndConvertJsScripts(jsFileNames);
        headerScriptInstances.addAll(jsScriptInstances.values());
        return headerScriptInstances;
    }

}
